1481D - AB Graph - CodeForces Solution


brute force constructive algorithms graphs greedy implementation *2000

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
using namespace std;
#define mod 998244353
#define oo 1000000010
const int N = 1010;
int n , m;
char grid[N][N];
int has[N][2];


void solve(){
	scanf("%d%d",&n,&m);
	for(int i = 0 ;i <= n;i++) has[i][0] = has[i][1] = -1;
	for(int i = 0 ;i < n;i++){
		scanf("%s",grid[i]);
		for(int j = 0  ;j < n;j++){
			if(j == i) continue;
			has[i][grid[i][j] - 'a'] = j;
		}
	}
	if(m & 1){
		puts("YES");
		for(int i = 0 ;i < m + 1;i++){
			if(i) putchar(' ');
			printf("%d",(i & 1) + 1);
		}
		puts("");
		return;
	}
	for(int i = 0 ;i < n;i++){
		for(int j = i + 1;j < n;j++){
			if(grid[i][j] == grid[j][i]){
				puts("YES");
				for(int k = 0 ;k < m + 1;k++){
					if(k) putchar(' ');
					printf("%d",(k & 1 ? i + 1 : j + 1));
				}
				puts("");
				return;
			}
		}
	}
	for(int i = 0 ;i < n;i++){
		for(int j = 0;j < n;j++){
		    if(i == j) continue;
			if(has[j][grid[i][j] - 'a'] == -1) continue;
			puts("YES");
			int cur = has[j][grid[i][j] - 'a'];
			if((m / 2) % 2 == 1){
				for(int k = 0 ;k < m + 1;k++){
					if(k) putchar(' ');
					if(k % 4 == 0)
						printf("%d",i + 1);
					else if(k % 4 == 2)
						printf("%d",cur + 1);
					else
						printf("%d",j + 1);
				}
				puts("");
				return;
			}
			printf("%d",j + 1);
			for(int k = 0 ;k < m / 2;k++){
				if(k & 1) printf(" %d",j + 1); else printf(" %d",cur + 1);
			}
			for(int k = 0 ;k < m / 2;k++){
				if(k & 1) printf(" %d",j + 1); else printf(" %d",i + 1);
			}
			puts("");
			return;
		}
	}
	puts("NO");
	return;
}

int main()
{
    //freopen("thu.inp","r",stdin);
    //freopen("thu.out","w",stdout);
	int t;
	scanf("%d",&t);
	while(t--)
	    solve();
	return 0;
}


Comments

Submit
0 Comments
More Questions

507B - Amr and Pins
379A - New Year Candles
1154A - Restoring Three Numbers
750A - New Year and Hurry
705A - Hulk
492B - Vanya and Lanterns
1374C - Move Brackets
1476A - K-divisible Sum
1333A - Little Artem
432D - Prefixes and Suffixes
486A - Calculating Function
1373B - 01 Game
1187A - Stickers and Toys
313B - Ilya and Queries
579A - Raising Bacteria
723A - The New Year Meeting Friends
302A - Eugeny and Array
1638B - Odd Swap Sort
1370C - Number Game
1206B - Make Product Equal One
131A - cAPS lOCK
1635A - Min Or Sum
474A - Keyboard
1343A - Candies
1343C - Alternating Subsequence
1325A - EhAb AnD gCd
746A - Compote
318A - Even Odds
550B - Preparing Olympiad
939B - Hamster Farm